package cn.wenhe9.hefengweather.logic.network

import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine

/**
 *@author DuJinliang
 *2021/10/1
 */
object HeFengWeatherNetWork {
    private val placeService = ServiceCreator.create<PlaceService>()

    private val weatherService = ServiceCreator.create<WeatherService>()

    suspend fun getLifeIndex(locationId: String) = weatherService.getLifeIndex(locationId).await()

    suspend fun getDailyWeather(locationId : String) = weatherService.getDailyWeather(locationId).await()

    suspend fun getRealtimeWeather(locationId : String) = weatherService.getRealtimeWeather(locationId).await()

    suspend fun searchPlaces(location : String) = placeService.searchPlaces(location).await()

    private suspend fun <T> Call<T>.await() : T {
        return suspendCoroutine { continuation ->
            enqueue(object : Callback<T> {
                override fun onResponse(call: Call<T>, response: Response<T>) {
                    val body = response.body()

                    if (body != null){
                        continuation.resume(body)
                    }else {
                        continuation.resumeWithException(RuntimeException("response body is null"))
                    }
                }

                override fun onFailure(call: Call<T>, t: Throwable) {
                    continuation.resumeWithException(t)
                }

            })
        }
    }
}